//
//  TimeUtils.swift
//  xz-app
//
//  Created by chen on 2025/5/6.
//
import Foundation

class TimeUtils {
    
    // 获取当前时间戳
    static func getCurrentTimestamp() -> Int64 {
        return Int64(Date().timeIntervalSince1970 * 1000)
    }
    
    // 时间戳转base64
    static func timestampToBase64() -> String {
        let timestampString = String(getCurrentTimestamp())
        if let data = timestampString.data(using: .utf8) {
            return data.base64EncodedString()
        }
        return ""
    }
    
    static func convertTimestampToDate(_ timestamp: Int64, _ format: String) -> String {
        // 创建日期格式化器
        let formatter = DateFormatter()
        formatter.dateFormat = format // 设置目标格式
        formatter.locale = Locale(identifier: "en_US_POSIX") // 确保格式化器使用标准区域设置
        formatter.timeZone = TimeZone(secondsFromGMT: 8) // 设置时区为 UTC

        // 将时间戳转换为 Date 对象
        let date = Date(timeIntervalSince1970: TimeInterval(timestamp))

        // 返回格式化后的日期字符串
        return formatter.string(from: date)
    }
    
    static func convertToYearMonthDayTimestamp(_ timestamp: Int64) -> Int64 {
        // 创建日期对象
        let date = Date(timeIntervalSince1970: TimeInterval(timestamp))
        
        // 创建日历对象
        var calendar = Calendar.current
        calendar.timeZone = TimeZone(secondsFromGMT: 8)! // 设置为 UTC 时区
        
        // 提取年月日部分
        let components = calendar.dateComponents([.year, .month, .day], from: date)
        
        // 生成仅包含年月日的新日期
        guard let yearMonthDayDate = calendar.date(from: components) else {
            return 0 // 如果无法生成日期，返回 0
        }
        
        // 转换为时间戳
        return Int64(yearMonthDayDate.timeIntervalSince1970)
    }
    
    static func isToday(_ timestamp: Int64) -> Bool {
        let date = Date(timeIntervalSince1970: TimeInterval(timestamp))
        return Calendar.current.isDateInToday(date)
    }

}
